﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using Controller;
using Model;

public partial class DattourStep1 : System.Web.UI.Page
{
    // public Hashtable hashObj = new Hashtable();
    public static string trigiaCb;
    // public static int soChoTrongHT;
    public static int soCho;
    // public static string hinhthucTT;

    // ID cuc tour
    public static string _idTour;
    public static string _idDattour = "VYCBook" + AppCommon.Common.ConvertDateTimetoString();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var idTour = Request.QueryString["Id"];
            if (!string.IsNullOrEmpty(idTour))
            {
                _idTour = idTour;
                BindDataTour();
            }
            setInitialRow();
            
        }
    }

    private void setInitialRow()
    {
        var dt = new DataTable();
        DataRow dr = null;

        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        dt.Columns.Add(new DataColumn("Column4", typeof(string)));
        dt.Columns.Add(new DataColumn("Column5", typeof(string)));
        dt.Columns.Add(new DataColumn("Column6", typeof(string)));
        dt.Columns.Add(new DataColumn("Column7", typeof(string)));
        dt.Columns.Add(new DataColumn("Column8", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dr["Column4"] = string.Empty;
        dr["Column5"] = string.Empty;
        dr["Column6"] = string.Empty;
        dr["Column7"] = string.Empty;
        dr["Column8"] = string.Empty;


        dt.Rows.Add(dr);

        // Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        gridViewInfo.DataSource = dt;
        gridViewInfo.DataBind();
    }

    protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList cbo1 = (DropDownList)e.Row.FindControl("cboGioiTinh1");
            DropDownList cbo2 = (DropDownList)e.Row.FindControl("cboLoaiKhach1");
            DropDownList cbo3 = (DropDownList)e.Row.FindControl("cboDoTuoi1");
            DropDownList cbo4 = (DropDownList)e.Row.FindControl("cboPhongDon1");
            Label lblTrigiaGv = (Label)e.Row.FindControl("lbTriGia1");

            BindDatatoDDL.BindTuoi(cbo3);
            BindDatatoDDL.BindLoaiKhach(cbo2);
            BindDatatoDDL.BindGioitinh(cbo1);
            BindDatatoDDL.BindPhongdon(cbo4);
            lblTrigiaGv.Text = String.Format("{0:###,###,##0}", litGiatour.Text).ToString();

        }
    }

    protected void TextChangedEvent(object sender, EventArgs e)
    {
        TextBox thisTextBox = (TextBox)sender;
        GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
        int row = thisGridViewRow.RowIndex;

        if (row == gridViewInfo.Rows.Count - 1 && gridViewInfo.Rows.Count < Convert.ToInt32(tbSlTongsokh.Text))
        {
            addNewRowToGrid();
        }
    }

    private void addNewRowToGrid()
    {
        int rowIndex = 0;
        int maxRow = Convert.ToInt32(tbSlTongsokh.Text.ToString()) + 1;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0 && dtCurrentTable.Rows.Count < maxRow)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    // extract the TextBox value
                    var box1 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[1].FindControl("tbGvHovaten");
                    var box2 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[2].FindControl("tbGvNgaysinh");
                    var box3 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[3].FindControl("tbGvDiachi");
                    var cbo1 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[4].FindControl("cboGioiTinh1");
                    var cbo2 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[5].FindControl("cboLoaiKhach1");
                    var cbo3 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[6].FindControl("cboDoTuoi1");
                    var cbo4 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[7].FindControl("cboPhongDon1");
                    var lblTriGia = (Label)gridViewInfo.Rows[rowIndex].Cells[8].FindControl("lbTriGia1");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                    dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                    dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                    dtCurrentTable.Rows[i - 1]["Column4"] = cbo1.Text;
                    dtCurrentTable.Rows[i - 1]["Column5"] = cbo2.Text;
                    dtCurrentTable.Rows[i - 1]["Column6"] = cbo3.Text;
                    dtCurrentTable.Rows[i - 1]["Column7"] = cbo4.Text;
                    dtCurrentTable.Rows[i - 1]["Column8"] = String.Format("{0:###,###,##0}", litGiatour.Text).ToString();
                    rowIndex++;
                }

                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                gridViewInfo.DataSource = dtCurrentTable;
                gridViewInfo.DataBind();
            }

        }
        else
        {
            Response.Write("ViewState is null");
        }
        // set previous Data on Postbacks
        setPreviousData();
    }

    private void setPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var box1 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[1].FindControl("tbGvHovaten");
                    var box2 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[2].FindControl("tbGvNgaysinh");
                    var box3 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[3].FindControl("tbGvDiachi");
                    var cbo1 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[4].FindControl("cboGioiTinh1");
                    var cbo2 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[5].FindControl("cboLoaiKhach1");
                    var cbo3 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[6].FindControl("cboDoTuoi1");
                    var cbo4 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[7].FindControl("cboPhongDon1");
                    var lblTriGia = (Label)gridViewInfo.Rows[rowIndex].Cells[8].FindControl("lbTriGia1");

                    box1.Text = dt.Rows[i]["Column1"].ToString();
                    box2.Text = dt.Rows[i]["Column2"].ToString();
                    box3.Text = dt.Rows[i]["Column3"].ToString();
                    cbo1.Text = dt.Rows[i]["Column4"].ToString();
                    cbo2.Text = dt.Rows[i]["Column5"].ToString();
                    cbo3.Text = dt.Rows[i]["Column6"].ToString();
                    cbo4.Text = dt.Rows[i]["Column7"].ToString();

                    if (cbo3.Text != "0")
                    {
                        lblTriGia.Text = trigiaCb;
                    }
                    else
                    {
                        if (cbo3.SelectedIndex == 0)
                            lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb))).ToString();
                        if (cbo3.SelectedIndex == 1)
                            lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb) * 75 / 100)).ToString();
                        if (cbo3.SelectedIndex == 2)
                            lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb) * 25 / 100)).ToString();
                        //lblTriGia.Text = trigiaCb;
                    }
                    rowIndex++;
                }
            }
        }
    }

    protected void tbSlNguoilon_TextChange(object sender, EventArgs e)
    {
        // tong khach hien tai
        int tongKhach = 0;

        // tong so nguoi lon
        int soNL = Convert.ToInt32(tbSlNguoilon.Text.ToString());
        // tong so tre em
        int soTreem = Convert.ToInt32(tbSlTreem.Text.ToString());
        // tong so tre nho
        int soTreNho = Convert.ToInt32(tbSlTrenho.Text.ToString());
        // tong so em be
        //int soEmBe = Convert.ToInt32(tbSlEmbe.Text.ToString());

        tongKhach += soNL + soTreem + soTreNho;
        tbSlTongsokh.Text = tongKhach.ToString();

    }
//    protected void tbSotrenho_OnTextChanged(object sender, EventArgs e)
//    {
//        tbTongsoKh.Text = "12";
//        tbTencongty.Text = "HEALALA";
//    }
    protected void btChapnhan_OnClick(object sender, EventArgs e)
    {
        // Nhan du lieu, xu ly validate
        var tongsokhach = tbSlTongsokh.Text;
        var songuoilon = tbSlNguoilon.Text;
        var sotreem = tbSlTreem.Text;
        var sotrenho = tbSlTrenho.Text;
        // Luu du lieu vao session
        if (soCho < Convert.ToInt32(tongsokhach))
        {
            litResult.Text =
                "<span class=\"text-danger\">** Số lượng khách lớn hơn số chỗ có thể đăng ký của tour. Vui lòng liên hệ để được tư vấn.</span>";
        }
        else
        {
             Session.Add("InfoGuest", GetDataKhachHang());// thong tin khach hang dat tour VYC11Model
             Session.Add("ListGuest", GetDanhsachDattour(0,0));
             // Di chuyen den step 2: Chon hinh thuc thanh toan
             Response.Redirect("~/" + "dattour/" + _idTour + "/hinhthuc-thanhtoan");
        }
        // Session.Add("InfoGuest", GetDataKhachHang());// thong tin khach hang dat tour VYC11Model
        // Session.Add("ListGuest", GetDanhsachDattour(0,0));
        // Di chuyen den step 2: Chon hinh thuc thanh toan
        // Response.Redirect("~/" + "dattour/" + _idTour + "/hinhthuc-thanhtoan");
    }

    /// <summary>
    /// Thuc hien Bind du lieu cho tour
    /// </summary>
    public void BindDataTour()
    {
        // 
        var controller = new VYC01Controller();
        var model = controller.GetById(_idTour);

        if (model.Count > 0)
        {
            litTieudetour.Text = model[0].TieuDe;
            litNgaykhoihanh.Text = model[0].NgayDi.ToString("dd/mm/yyyy");
            litNoikhoihanh.Text = GetTenDiaDiem(model[0].IdNoiDi);
            litSocho.Text = model[0].SoCho.ToString();
            soCho = Convert.ToInt32(model[0].SoCho);

            litGiatour.Text = String.Format("{0:###,###,##0}", model[0].Gia).ToString();

            litGiatourNL1.Text = String.Format("{0:###,###,##0}", model[0].Gia).ToString();
            litGiatourNL2.Text = String.Format("{0:###,###,##0}", model[0].Gia).ToString();
            litGiatourNL3.Text = String.Format("{0:###,###,##0}", model[0].Gia).ToString();

            litGiatourTE1.Text = String.Format("{0:###,###,##0}", Convert.ToDecimal(model[0].Gia)*75/100).ToString();
            litGiatourTE2.Text = String.Format("{0:###,###,##0}", Convert.ToDecimal(model[0].Gia)*75/100).ToString();
            litGiatourTE3.Text = String.Format("{0:###,###,##0}", Convert.ToDecimal(model[0].Gia)*75/100).ToString();

            litGiatourTN1.Text = String.Format("{0:###,###,##0}", Convert.ToDecimal(model[0].Gia) * 25/100).ToString();
            litGiatourTN2.Text = String.Format("{0:###,###,##0}", Convert.ToDecimal(model[0].Gia) * 25/100).ToString();
            litGiatourTN3.Text = String.Format("{0:###,###,##0}", Convert.ToDecimal(model[0].Gia) * 25/100).ToString();

        }
    }

    /// <summary>
    /// Lay du lieu cho khach hang bang cach kiem tra dia chi email xem khach hang do co ton
    /// tai trong co so du lieu chua. 
    ///  - Neu chua co thi tao du lieu moi cho khach hang
    ///  - Neu co roi thi thuc hien thong bao cho khach hang roi tien hanh
    ///  cap nhat du lieu moi cho khach hang.
    /// </summary>
    /// <returns></returns>
    public ModelVYC11 GetDataKhachHang()
    {
        var model = new ModelVYC11();
        
        // Lay du lieu'
        var tenCty = tbTencongty.Text;
        var hovaten = tbHovaten.Text;
        var diachi = tbDiachi.Text;
        var dienthoai = tbDienthoai.Text;
        var email = tbEmail.Text;
        var didong = tbDidong.Text;
        var masothue = tbMasothue.Text;
        var tongsokhach = tbSlTongsokh.Text;
        var socmnd = tbCmnd.Text;
        var chuthich = tbGhichu.Text;
        
        model.HoTen = hovaten;
        model.SDT = dienthoai;
        model.Email = email;
        model.TenCongTy = tenCty;
        model.DiaChi = diachi;
        model.DiDong = didong;
        model.MST = masothue;
        model.SoLuong = Convert.ToInt32(tongsokhach);
        model.Id = _idDattour;
        model.IdTour = _idTour;
        model.CMND = socmnd;
        model.NgayCapNhat = DateTime.Now;
        model.ChuThich = chuthich;

        return model;
    }

    public List<ModelVYC12> GetDanhsachDattour(int sochotrong, int tongsodat)
    {
        var list = new List<ModelVYC12>();
        if (gridViewInfo.Rows.Count > 0)
        {
            var dt = new DataTable();
            foreach (GridViewRow gvRow in gridViewInfo.Rows)
            {
                var model = new ModelVYC12();
                var tbHotenGv = (TextBox)gvRow.FindControl("tbGvHovaten");
                var hoten = tbHotenGv.Text;
                model.HoTen = hoten;

                var tbNgaysinhGv = (TextBox)gvRow.FindControl("tbGvNgaysinh");
                var ngaysinh = tbNgaysinhGv.Text;
                model.NgaySinh = DateTime.Parse(ngaysinh);

                var tbDiachiGv = (TextBox)gvRow.FindControl("tbGvDiachi");
                var diachi = tbDiachiGv.Text;
                model.DiaChi = diachi;
                // Gioi tinh
                var cboGioitinhGv = (DropDownList)gvRow.FindControl("cboGioiTinh1");
                var idGt = Convert.ToInt32(cboGioitinhGv.SelectedValue);
                var gioiTinh = cboGioitinhGv.SelectedItem.Value.ToString();
                model.GioiTinh = Convert.ToInt32(gioiTinh);
                // Loai khach
                var cboLoaikhachGv = (DropDownList)gvRow.FindControl("cboLoaiKhach1");
                var idLk = Convert.ToInt32(cboLoaikhachGv.SelectedValue);
                var loaiKhach = cboLoaikhachGv.SelectedItem.Value.ToString();
                model.IdLoaiKhach = Convert.ToInt32(loaiKhach);
                // Do tuoi
                var cboDotuoiGv = (DropDownList)gvRow.FindControl("cboDotuoi1");
                var idDt = Convert.ToInt32(cboDotuoiGv.SelectedValue);
                var dotuoi = cboDotuoiGv.SelectedItem.Value.ToString();
                model.IdDoTuoi = Convert.ToInt32(dotuoi);
                // Phong don
                var cboPhongDonGv = (DropDownList)gvRow.FindControl("cboPhongDon1");
                var idPd = Convert.ToInt32(cboPhongDonGv.SelectedValue);
                var phongDon = cboPhongDonGv.SelectedItem.Text.ToString();
                model.PhongDon = phongDon;
                // Tri gia
                Label lbTriGiaGv = (Label)gvRow.FindControl("lbTriGia1");
                string trigia = lbTriGiaGv.Text.ToString();
                model.GiaTien = Convert.ToDecimal(trigia);

                model.IdDatTour = _idDattour;                

                list.Add(model);
            }
        }
        return list;
    }

    public string GetTenDiaDiem(int id)
    {
        var controller = new VYC24Controller();
        var model = controller.GetById(id);
        return model.Count > 0 ? model[0].Ten : "Not Avaiable";
    }

}